package com.gouaixin.bee.beeframework2.extra.floatView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;

import com.gouaixin.bee.beeframework2.MyConfig;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;

public class FloatWindowService extends Service {

    Context context = FloatWindowService.this;

    @Override
    public void onCreate() {
        super.onCreate();

        PreferencesUtils.putLong(context, "bannerTime", System.currentTimeMillis() + MyConfig.Banner);



    }

    /**
	 * 用于在线程中创建或移除悬浮窗。
	 */
	private Handler handler = new Handler();

	/**
	 * 定时器，定时进行检测当前应该创建还是移除悬浮窗。
	 */
	private Timer timer;

    long runTime;//悬浮窗运行的时间
    long runEndTime=60;//悬浮窗运行截至的时间

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {



		// 开启定时器，每隔0.5秒刷新一次
		if (timer == null) {
			timer = new Timer();
			timer.scheduleAtFixedRate(new RefreshTask(), 0, 1000);
		}
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

        mLog.e("FloatWindowService：onDestroy");

        if(runTime<=runEndTime){
            Intent localIntent = new Intent();
            localIntent.setClass(this, FloatWindowService.class);  //销毁时重新启动Service
            this.startService(localIntent);
        }else {
            mLog.e("FloatWindowService：彻底干掉了");
            // Service被终止的同时也停止定时器继续运行
		timer.cancel();
		timer = null;
        }


	}

	class RefreshTask extends TimerTask {

		@Override
		public void run() {
			// 当前界面是桌面，且没有悬浮窗显示，则创建悬浮窗。
			if ((isHome()||isCurrentAppTop()) && !MyWindowManager.isWindowShowing()) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						MyWindowManager.createSmallWindow(getApplicationContext());
					}
				});
			}
			// 当前界面不是桌面，且有悬浮窗显示，则移除悬浮窗。
			else if (!(isHome()||isCurrentAppTop()) && MyWindowManager.isWindowShowing()) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						MyWindowManager.removeSmallWindow(getApplicationContext());
						MyWindowManager.removeBigWindow(getApplicationContext());
					}
				});
			}
			// 当前界面是桌面，且有悬浮窗显示，则更新内存数据。
			else if ((isHome()||isCurrentAppTop()) && MyWindowManager.isWindowShowing()) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						MyWindowManager.updateUsedPercent(getApplicationContext());
					}
				});
			}

            runTime=System.currentTimeMillis();
            runEndTime=PreferencesUtils.getLong(context,"bannerTime",0);
            long jaingeTime=(runEndTime-runTime)/1000;
            mLog.e("FloatWindowService:runTime="+jaingeTime);
            if(runTime>=runEndTime){
                mLog.e("到了20分钟，移除悬浮窗,干掉自己");
                MyWindowManager.removeSmallWindow(getApplicationContext());
                stopSelf();
            }
		}
	}

	/**
	 * 判断当前界面是否是桌面
	 */
	private boolean isHome() {
		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		return getHomes().contains(rti.get(0).topActivity.getPackageName());
	}
	
	/**
	 * 判断手机当前界面是否是该程序
	 */
	private boolean isCurrentAppTop(){
		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		return rti.get(0).topActivity.getPackageName().equals(getPackageName());
	}

	/**
	 * 获得属于桌面的应用的应用包名称
	 * 
	 * @return 返回包含所有包名的字符串列表
	 */
	private List<String> getHomes() {
		List<String> names = new ArrayList<String>();
		PackageManager packageManager = this.getPackageManager();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		for (ResolveInfo ri : resolveInfo) {
			names.add(ri.activityInfo.packageName);
		}
		return names;
	}
}
